//
//  HRRetweetCollectionView.swift
//  weiBo
//
//  Created by helong on 16/7/15.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
let itemMargin: CGFloat = 5
private let retweetCollectionView: String = "retweetCollectionView"
class HRRetweetCollectionView: UICollectionView {
    //  item的宽度
    let itemWidth = (screenWidth() - 2 * (Margin + itemMargin)) / 3
    //  接收数据接口
    var pic_urls:[HRRetweetPicture]?{
        //  给子控件赋值
        didSet{
            //  设置collection的大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(collectionItemSize(pic_urls?.count ?? 0))
            }
            
            reloadData()

        }
        
    }

    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //  如果外界不传layout参数我们自己初始化一个layout,防止程序崩溃
        let flowLayout = UICollectionViewFlowLayout()
        //  设置item的大小
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        //  注册cell
        registerClass(HRRetweetCollectionViewCell.self, forCellWithReuseIdentifier: retweetCollectionView)
    }

     // MARK: - 添加子控件,设置约束
    private func setupUI(){
       backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        printLog()
        //  只有遵守协议之后才能设置此代理
        dataSource = self
        delegate = self
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     // MARK: - 根据请求到的转发图片的数量计算collectionview的大小
    private func collectionItemSize(count: Int) -> CGSize{
        
        //  行数
        let rows = (count - 1) / 3 + 1
        let cols = count > 3 ? 3 : count
        
            //  collectionView的宽度
           let collectionViewWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin

        //  collectionView的高度
       let collectionViewHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
  
//        let size = CGSize(width: collectionViewWidth, height: collectionViewHeight)
        let size = CGSizeMake(collectionViewWidth, collectionViewHeight) //有什么区别
        return size
    
    }
}

     // MARK: - 实现数据源
extension HRRetweetCollectionView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(retweetCollectionView, forIndexPath: indexPath) as! HRRetweetCollectionViewCell
      
        cell.pic_url = pic_urls![indexPath.item]
//        print(pic_urls![indexPath.item])
//        cell.backgroundColor = randomColor()
        printLog()
        return cell
    }
     // MARK: - 仿照SDPhotoBrowser实现点击图片发达的效果
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = (pic_urls?.count)!
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
     // MARK: - 实现SDPhotoBrowser的两个必选的代理方法
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
      
        let urlStr = pic_urls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
        
    }
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {

        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! HRRetweetCollectionViewCell
        return cell.retweetPicture.image
    }
    


}

 // MARK: - 自定义cell
class HRRetweetCollectionViewCell: UICollectionViewCell{
    
    var pic_url: HRRetweetPicture?{
        didSet{
            //  给子控件赋值
            guard let thumbnail_pic = pic_url?.thumbnail_pic else{
                return
            }
           //   判断是否显示Gif图片
            GIFMark.hidden = !thumbnail_pic.hasSuffix(".gif")
            
            retweetPicture.sd_setImageWithURL(NSURL(string: thumbnail_pic))
        }
    }
    //  懒加载图片框
    private lazy var retweetPicture: UIImageView = {
       let img = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  设置图片的填充模式
        img.contentMode = UIViewContentMode.ScaleAspectFill
        //  剪切多余的边
        img.clipsToBounds = true
        return img
    }()
    //  懒加载GIF图标
    private lazy var GIFMark: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
      
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // MARK: - 添加控件,设置约束
    private func setupCell(){
        addSubview(retweetPicture)
        addSubview(GIFMark)
        
        retweetPicture.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        GIFMark.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(retweetPicture)
            make.bottom.equalTo(retweetPicture)
        }
        
    }
}











